export default class extends think.Service {
  constructor() {
    super();
    this.operationModel = this.db['sys_operation'];
  }

  /**
   * 获取权限标识数据
   * @param {*} data {page,pageSize}
   */
  async getOperation(data) {
    data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
    const Op = this.db.sequelize.Op;
    const where = {};

    if (data.name) {
      where.name = {
        [Op.like]: '%' + data.name + '%'
      };
    }
    if (data.code) {
      where.code = {
        [Op.like]: '%' + data.code + '%'

      };
    }
    const condition = {
      where: {},
      limit: parseInt(data.pageSize),
      offset: parseInt(data.start)
    };
    try {
      return await this
        .operationModel
        .findAndCountAll(condition);
    } catch (error) {
      return this
        .exceptionService
        .handleError(error);
    }
  }

  /**
   * 新增/修改 权限标识
   * @param {*} data
   */
  async upDataOperation(data) {
    const Op = this.db.Sequelize.Op;

    try {
      const olderOperation = await this
        .operationModel
        .findOne({
          where: {
            [Op.or]: {
              name: data.name,
              code: data.code
            }
          }
        });
      if (data.id) { // 编辑
        if (olderOperation && olderOperation.id !== data.id) {
          return {error: '数据不匹配，请重试'};
        }
        return await this
          .operationModel
          .update(data, {
            where: {
              id: data.id
            }
          });
      } else { // 新增
        if (olderOperation) {
          return {error: '标识名称或标识码重复，请重试'};
        }
        return await this
          .operationModel
          .create(data);
      }
    } catch (error) {
      return this
        .exceptionService
        .handleError(error);
    }
  }

  /**
   * 删除权限标识
   * @param {*} data
   */
  async delOperation(data) {
    const where = {
      id: data.id
    };
    try {
      return await this
        .operationModel
        .destroy({where: where});
    } catch (error) {
      return this
        .exceptionService
        .handleError(error);
    }
  }

  async getOperationAll() {
    try {
      return this.operationModel.findAll();
    } catch (error) {
      return this
        .exceptionService
        .handleError(error);
    }
  }
}
